package com.sfdk.graphics.animation
{
import com.sfdk.data.RectangleID;
import com.sfdk.io.GenericIO;

import flash.display.BitmapData;
import flash.geom.Point;
import flash.geom.Rectangle;
import flash.net.registerClassAlias;
import flash.utils.ByteArray;
import flash.utils.Dictionary;

public class AnimatedObject extends GenericIO
	{
		
		private var _animationData : Dictionary;
		private var _animationTile : Vector.<BitmapData>;
		
		public function AnimatedObject(animatedObjectPath : String)
		{
			_animationTile = new Vector.<BitmapData>();
			super(animatedObjectPath, GenericIO.DATA_FILE);
		}
		
		override protected function init() : void
		{
			super.init();
			
			registerClassAlias("com.sfdk.data.RectangleID", RectangleID);
			
			var byteArray : ByteArray = getByteData();
			byteArray.inflate();
			byteArray.position = 0;
			
			var imageWidth : int = byteArray.readUnsignedInt();
			var imageHeight : int = byteArray.readUnsignedInt();
			var imageSize : int = byteArray.readUnsignedInt();
			
			var imageByteArray : ByteArray = new ByteArray();
			byteArray.readBytes(imageByteArray,0,imageSize);
			
			var imageBitmapData : BitmapData = new BitmapData(imageWidth, imageHeight);
			imageBitmapData.setPixels(new Rectangle(0,0,imageWidth, imageHeight), imageByteArray);
			
			try
			{
				var splicingData : Array = byteArray.readObject() as Array;
				var animationData : Array = byteArray.readObject() as Array;
			}
			catch(e : TypeError)
			{
				trace(e);
			}
			
			// Splicing handling
			splicingData.sortOn("id");
			var splicingObject : RectangleID;
			var splicingBitmap : BitmapData;
			var splicingIndex : int;
			for each (splicingObject in splicingData)
			{
				splicingBitmap = new BitmapData(splicingObject.width, splicingObject.height);
				splicingBitmap.copyPixels(imageBitmapData, splicingObject, new Point());
				_animationTile[splicingIndex] = splicingBitmap;
				splicingIndex++;
			}
			
			var actionChooserDP : Vector.<String> = new Vector.<String>(["Statique", "Marche"]);
			var faceChooserDP : Vector.<String> = new Vector.<String>(["Face", "Dos", "Gauche"]);
			var currFace : String;
			var currAction : String;
			var animationIndex : int;
			var subAnimationArray : Array;
			
			for each(currFace in faceChooserDP)
			{
				for each(currAction in actionChooserDP)
				{
					subAnimationArray = animationData[animationIndex];
					_animationData[currAction+"_"+currFace] = subAnimationArray;
					animationIndex++;
				}
			}
		}
		
		public function getAnimationData(face : String, action : String) : Array
		{
			return _animationData[action+"_"+face];
		}
		
		public function get maxIndex(): int
		{
			return _animationTile.length;
		}
		
		public function getView(tileID : int) : BitmapData
		{
			if(tileID >= _animationTile.length)
				return null;
			return _animationTile[tileID];
		}
	}
}